//
//  SYZiYuanSecondLevelViewController.m
//  SanYiTeaching
//
//  Created by 郑浩然 on 2019/5/28.
//  Copyright © 2019年 SanYi. All rights reserved.
//

#import "SYZiYuanSecondLevelViewController.h"
#import "SYCollectionTopView.h"
#import "SYCollectionView.h"
#import "SYCollectionTableView.h"
#import "SYNewAlerView.h"
#import "SYSeondaryView.h"
#import "SYZiYuanSecondLevelViewController.h"
#import "SYBaiBanFuDaoViewController.h"
#import "SYDrawViewController.h"

@interface SYZiYuanSecondLevelViewController () <SYCollectionTopViewDelegate>

@property (strong, nonatomic) SYTopView *topView;
@property (strong, nonatomic) SYCollectionTopView *shearView;

@property (strong, nonatomic) UITableView *curTableView;

@property (strong, nonatomic) SYCollectionView *collectionView;

@property (strong, nonatomic) SYCollectionTableView *tableView;//表

@property (strong, nonatomic) NSMutableArray *dataArr;

@property (strong, nonatomic) SYNewAlerView *alerView;

@property (strong, nonatomic) SYSeondaryView *seondaryView;

@property (assign, nonatomic) BOOL isUpdate;//是否请求过数据

@property (strong, nonatomic) SYNoLabel *nolab;

@property (strong, nonatomic) SYBackTopView *backTopView;

@property (strong, nonatomic) SYZiYuanSecondLevelViewController *ziyuanVC;
@property (nonatomic ,strong) SYBaiBanFuDaoViewController *interactionVC;

@property (assign, nonatomic) BOOL isSelect;//是否是惦记了录制按钮

@end

@implementation SYZiYuanSecondLevelViewController
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    _nolab = [[SYNoLabel alloc] initWithNameStr:@"" contView:self.view];
    [self initUpUIKit];
    [_nolab mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.shearView.mas_bottom);
        make.left.bottom.right.equalTo(self.view);
    }];
//    if ([self.functionModel.titleName containsString:@"微课"]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(luzhiweike:) name:@"luzhiweike" object:nil];
    
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(huaBanShuaXinRequest) name:@"huaBan" object:nil];
//    }
    
}

// 从画板回来刷新数据
-(void)huaBanShuaXinRequest{
    
    [self requestData:self.functionModel.titleName];

}
- (void)luzhiweike:(NSNotification *)info{
    if (self.isSelect) {
        NSString *pathFiel = [info.userInfo objectForKey:@"path"];
        self.isSelect = NO;
        [MBProgressHUD mj_showMessage:@"上传视频"];
        [SYRequestAPI zy_requestSaveResource:self.sortId path:pathFiel isTinyClass:@"1" success:^(BOOL isSuccess) {
            [MBProgressHUD mj_hideHUD];
            [MBProgressHUD zr_showError:@"上传成功，因网络延迟，一分钟后请重新进入页面"];
        } fail:^(NSError *error) {
            [MBProgressHUD mj_hideHUD];
            [MBProgressHUD zr_showError:error.domain];
        }];
    }
    
    
}
- (void)initUpUIKit {
    

    [self.view addSubview:self.backTopView];
    [self.backTopView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.height.mas_equalTo(44);
    }];
    [self.view addSubview:self.shearView];
    self.shearView.delegate = self;
    [self.shearView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.backTopView.mas_bottom).offset(0);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(44);
    }];
    
    
    [self addCollection];
    [self addTableView];
//    [self viewDidSlidInto];
    
}
- (void)viewDidSlidInto {
    [self modifyTheState];
    //TOP
   // if (self.isUpdate == NO) {
        [self requestData:self.functionModel.titleName];
   // }
    
}
#pragma mark - 修改标题栏和搜索框
- (void)modifyTheState {
    _backTopView.titleLab.text = self.nameStr;
    _shearView.function = self.functionModel;
    
}

- (void)requestData:(NSString *)titleName {
    __weak typeof(self) weakSelf = self;
    if ([titleName isEqualToString:@"我的收藏"]) {
        NSString *isTinyClass = @"0";
        if ([titleName isEqualToString:@"我的收藏"] ) {
            isTinyClass = @"1";
        }
        [MBProgressHUD mj_showMessage:nil toView:self.view];
        [SYRequestAPI zy_resourceCollectionCollectionListPageIndex:0 pageSize:1000 sortPid:self.sortId isTinyClass:isTinyClass onlySort:@"0" success:^(NSMutableArray *listArr) {
            weakSelf.dataArr = listArr;
            weakSelf.isUpdate = YES;
            [MBProgressHUD mj_hideHUDForView:self.view];
            if (listArr.count == 0) {
                weakSelf.nolab.hidden = NO;
                weakSelf.tableView.hidden = YES;
                weakSelf.collectionView.hidden = YES;
                [weakSelf requestUpdate:weakSelf.dataArr];
            } else {
                [weakSelf requestUpdate:weakSelf.dataArr];
            }
            
            
        } fail:^(NSError *error) {
            [MBProgressHUD mj_hideHUDForView:self.view];
            weakSelf.isUpdate = NO;
            weakSelf.nolab.hidden = NO;
            weakSelf.tableView.hidden = YES;
            weakSelf.collectionView.hidden = YES;
        }];
    } else if ([titleName isEqualToString:@"我的作品"] || [titleName isEqualToString:@"我的微课"]) {
        NSString *isTinyClass = @"0";
        if ([titleName isEqualToString:@"我的微课"] ) {
            isTinyClass = @"1";
        }
        [MBProgressHUD mj_showMessage:nil toView:self.view];
        
        [SYRequestAPI zy_requestMyResourceListPageIndex:0 pageSize:1000 sortId:self.sortId isTinyClass:isTinyClass onlySort:@"" keyWord:@"" success:^(NSMutableArray *listArr) {
            weakSelf.dataArr = listArr;
            weakSelf.isUpdate = YES;
            [MBProgressHUD mj_hideHUDForView:self.view];
            if (listArr.count == 0) {
                weakSelf.nolab.hidden = NO;
                weakSelf.tableView.hidden = YES;
                weakSelf.collectionView.hidden = YES;
                [weakSelf requestUpdate:weakSelf.dataArr];
            } else {
                [weakSelf requestUpdate:weakSelf.dataArr];
            }
        } fail:^(NSError *error) {
            [MBProgressHUD mj_hideHUDForView:self.view];
            [weakSelf requestUpdate:[NSMutableArray array]];
            weakSelf.isUpdate = NO;
            weakSelf.nolab.hidden = NO;
            weakSelf.tableView.hidden = YES;
            weakSelf.collectionView.hidden = YES;
        }];
    }
}

- (void)requestUpdate:(NSMutableArray *)listArr {
    [self.collectionView subUpViewArr:listArr vc:self WithIsFrom:self.isFrom];
    [self.tableView subUpViewArr:listArr vc:self WithIsFrom:self.isFrom];
}



#pragma mark - set && get

- (SYBackTopView *)backTopView {
    if (!_backTopView) {
        _backTopView = [[SYBackTopView alloc] initWithTitleName:self.nameStr baseView:self.view];
        _backTopView.backgroundColor = [UIColor colorWithHexString:@"F8F8F8"];
    }
    return _backTopView;
}

- (SYTopView *)topView {
    if (!_topView) {
        _topView = [[SYTopView alloc] init];
        _topView.titleLab.text = @"我的收藏";
        _topView.backgroundColor = [UIColor colorWithHexString:@"F8F8F8"];
    }
    return _topView;
}
- (SYCollectionTopView *)shearView {
    if (!_shearView) {
        _shearView = [[SYCollectionTopView alloc] init];
        
    }
    return _shearView;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (void)addCollection {
    __weak typeof(self) weakSelf = self;

    self.collectionView = [[SYCollectionView alloc] init];
    self.collectionView.titleName = self.functionModel.titleName;
    self.collectionView.isChar = self.isChar;
    self.collectionView.isFrom = self.isFrom;
    self.collectionView.chooseZiYuanBlock = ^(SYCollectionModel *model) {
        if (weakSelf.chooseYuanRetureBlock) {
            weakSelf.chooseYuanRetureBlock(model);
        }
    };
    self.collectionView.typePid = self.sortId;
    
    
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.shearView.mas_bottom);
        make.left.bottom.right.equalTo(self.view);
    }];
    if ([self.functionModel.titleName isEqualToString:@"我的微课"]) {//我的微课数据源
        self.dataArr = [[SYCollectionModel alloc] weikeshuju];
        self.collectionView.stant = SYCollectionViewTypeWeiKe;
    } else {
        if ([self.functionModel.titleName isEqualToString:@"我的作品"]) {
            self.collectionView.stant = SYCollectionViewTypeMinWenJian;
        } else if ([self.functionModel.titleName isEqualToString:@"我的收藏"]) {
            self.collectionView.stant = SYCollectionViewTypeShouCang;
        }
        self.dataArr = [[SYCollectionModel alloc] monishuju];
    }
    //TOP
    //    [self.collectionView subUpViewArr:self.dataArr vc:self];
    
    
    self.collectionView.block = ^(SYCollectionViewType type, SYCollectionModel *model) {
        [weakSelf handleCallbackMethod:type collectionModel:model];
    };
    
}
//处理刷新过来的数据
- (void)handleCallbackMethod:(SYCollectionViewType)type collectionModel:(SYCollectionModel *)model {
    switch (type) {
        case SYCollectionViewTypeAll://删除刷新数据
            //            [self.tableView subUpViewArr:self.dataArr vc:self];
            //            [self.collectionView subUpViewArr:self.dataArr vc:self];
            [self requestData:self.functionModel.titleName];
            break;
        case SYCollectionViewTypeWeiKe://微课程
        {
            self.seondaryView = [[SYSeondaryView alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.view.frame)+20, 0, CGRectGetWidth(self.view.frame), APP_HEIGHT - 20)];
            
            [self.view addSubview:self.seondaryView];
            
            [self.view setNeedsUpdateConstraints];
            __weak typeof(self) weakSelf = self;
            [self.seondaryView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(self.view.mas_left);
                make.width.mas_equalTo(self.view.mas_width);
                make.height.mas_equalTo(APP_HEIGHT-20);
                make.top.equalTo(self.view.mas_top);
            }];
            
            [UIView animateWithDuration:kAnimate animations:^{
                [self.view layoutIfNeeded];
            } completion:^(BOOL finished) {
                [weakSelf.seondaryView viewSlidIntoSunbVC:self];
            }];
            
            [UIView animateWithDuration:1 animations:^{
                [weakSelf.seondaryView.superview layoutIfNeeded];
                
            }];
            
        }
            break;
            
        case SYCollectionViewTypeNewAddWenJianJia://新建文件夹
        {
            __weak typeof(self) weakSelf = self;
            self.ziyuanVC = [[SYZiYuanSecondLevelViewController alloc] init];
            [self.view addSubview:self.ziyuanVC.view];
            self.ziyuanVC.view.frame = CGRectMake(CGRectGetWidth(self.view.frame)+20, 0, CGRectGetWidth(self.view.frame), APP_HEIGHT - 20);
            self.ziyuanVC.functionModel = self.functionModel;
            self.ziyuanVC.sortId = model.zyid;
            
            
            [UIView animateWithDuration:kAnimate animations:^{
                [self.ziyuanVC.view mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(self.view.mas_left);
                    make.width.mas_equalTo(self.view.mas_width);
                    make.height.mas_equalTo(APP_HEIGHT-20);
                    make.top.equalTo(self.view.mas_top);
                }];
            } completion:^(BOOL finished) {
                [weakSelf.ziyuanVC viewDidSlidInto];
            }];
        }
            
            break;
            
        default:
            break;
    }
}

- (void)addTableView {
    //表
    self.tableView = [[SYCollectionTableView alloc] init];
    self.tableView.titleName = self.functionModel.titleName;
    self.tableView.typePid = self.sortId;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.shearView.mas_bottom);
        make.left.bottom.right.equalTo(self.view);
    }];
    self.tableView.hidden = YES;
    if ([self.functionModel.titleName isEqualToString:@"我的微课"]) {//我的微课数据源
        
        self.tableView.stats = SYCollectionViewTypeWeiKe;
    } else {
        if ([self.functionModel.titleName isEqualToString:@"我的作品"]) {
            self.tableView.stats = SYCollectionViewTypeMinWenJian;
        } else if ([self.functionModel.titleName isEqualToString:@"我的收藏"]) {
            self.tableView.stats = SYCollectionViewTypeShouCang;
        }
        
    }
    //TOP
    [self.tableView subUpViewArr:self.dataArr vc:self WithIsFrom:self.isFrom];
    
    
    __weak typeof(self) weakSelf = self;
    self.tableView.block = ^(SYCollectionViewType type, SYCollectionModel *model) {
        [weakSelf handleCallbackMethod:type collectionModel:model];
    };
    
}

#pragma mark - collectiontopdelegate
- (void)selectType:(SYCollectionTopType)type {
    switch (type) {
        case SYCollectionTopTypeAdd://添加文件夹
        {
            __weak typeof(self) weakSelf = self;
            _alerView = [[SYNewAlerView alloc] init];
            if ([self.functionModel.titleName isEqualToString:@"我的微课"]) {
                [_alerView showAler:_alerView titleName:@"新建微课包" textFielPlo:@"微课包名称"];
            } else {
                [_alerView showAler:_alerView titleName:@"新建文件夹" textFielPlo:@"新建文件夹"];
            }
            
            _alerView.block = ^(NSString *titleName) {//先这样写着。到时候在更改
                [weakSelf requestDataAddDirectoryName:titleName];
            };
        }
            break;
        case SYCollectionTopTypeTab://显示表格
        {
            if (self.dataArr.count == 0) {
                _nolab.hidden = NO;
            } else {
                self.tableView.hidden = YES;
                self.collectionView.hidden = NO;
            }
            
        }
            break;
        case SYCollectionTopTypeCollection://显示网格
        {
            if (self.dataArr.count == 0) {
                _nolab.hidden = NO;
            } else {
                self.tableView.hidden = NO;
                self.collectionView.hidden = YES;
            }
        }
            break;
        case SYCollectionTopTypeUpload://上传
        {
            
        }
            break;
        case SYCollectionTopTypePaiZhao://拍照
        {
            
        }
            break;
        case SYCollectionTopTypeZhaoPian://照片
        {
            
        }
            break;
        case SYCollectionTopTypeLiuLan://浏览
        {
            
        }
            break;
        case SYCollectionTopTypeLuWeiKe://录制微课
        {
            [self weiKeLuPing];
        }
            break;
            // 画板
        case SYCollectionTopTypeHuaBan:
        {
                [self goTuHuaBanVC];
        }
            break;
        default:
            break;
    }
}
// 跳转到画板页面
-(void)goTuHuaBanVC{
    SYDrawViewController *VC =[[SYDrawViewController alloc]init];
//    VC.modalPresentationStyle = UIModalPresentationOverFullScreen;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入标题名字" preferredStyle:UIAlertControllerStyleAlert];
    //增加确定按钮；
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
      //获取第1个输入框；
      UITextField *userNameTextField = alertController.textFields.firstObject;
      SYDrawViewController *VC =[[SYDrawViewController alloc]init];
        VC.titileName = userNameTextField.text;
        VC.sortId = self.sortId;
        //    VC.modalPresentationStyle = UIModalPresentationOverFullScreen;
      UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:VC];
      nav.modalPresentationStyle = UIModalPresentationOverFullScreen;
            //    [self.view addSubview:playerVC.view];
      [self presentViewController:nav animated:YES completion:^{
            //        [nav setNewOrientation:YES];
      }];
              
      
    }]];
    
    //增加取消按钮；
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];

      //定义第一个输入框；
      [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入标题名字";
      }];

    
    [self presentViewController:alertController animated:true completion:nil];
    
    
}
- (void)weiKeLuPing {
    [SYRequestAPI bb_TutorServiceImInfoToken:Token success:^(id  _Nonnull dataList) {
        //这里需要房间号，名字，登录账号（生成的）
        [MBProgressHUD mj_hideHUDForView:self.view];
        self->_interactionVC = [[SYBaiBanFuDaoViewController alloc] init];
        self->_isSelect = YES;
        //TOP 先写死
        //                SaveDataToNSUserDefaults([dataList nilObjectForKey:@"imId"], @"independence_ios");
        self->_interactionVC.userName = [dataList nilObjectForKey:@"imId"];
        self->_interactionVC.userSig = [dataList nilObjectForKey:@"userSig"];
        //NSInteger room = arc4random() %100;
        
        self->_interactionVC.isChat = YES;
        self->_interactionVC.isWeiKe = YES;
        NSString *roomId = [NSString stringWithFormat:@"9%@",GetDataFromNSUserDefaults(AcountIDDefalut)];
        
        self->_interactionVC.roomId = roomId;//SJStringWithFormat(room);
        self->_interactionVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [self presentViewController:self->_interactionVC animated:YES completion:nil];
        
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self.view];
        [MBProgressHUD zr_showError:error.domain];
        //            YLSLog(@"----请求错误");
    }];
}
//创建新目录
- (void)requestDataAddDirectoryName:(NSString *)name {
    [MBProgressHUD mj_showMessage:nil toView:self.view];
    
    NSString *category = nil;
    if ([_functionModel.titleName isEqualToString:@"我的作品"]) {
        category = @"0";
    } else if ([_functionModel.titleName isEqualToString:@"我的微课"]) {
        category = @"1";
    } else if ([_functionModel.titleName isEqualToString:@"我的收藏"]) {
        category = @"2";
    }
    
    __weak typeof(self) weakSelf = self;
    [SYRequestAPI zy_requestMyResourceAddDirectoryName:name typePid:self.sortId category:category success:^(BOOL isSuccess) {
        [MBProgressHUD mj_hideHUDForView:weakSelf.view];
        
        [NSObject executeRunloop:^{
            [MBProgressHUD zr_showError:@"添加成功"];
            [weakSelf requestData:weakSelf.functionModel.titleName];
        } afterDelay:1];
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:weakSelf.view];
        [MBProgressHUD zr_showError:error.message];
    }];
    
}

@end
